#!/usr/bin/env python
# -*- coding: utf-8 -*

from clutter import Label
from box import LBox
import os
import alwaysontop
import gobject

from urllib import urlopen

gare_from = "BFX"
gare_to = "PAA"
refresh_seconds = 10

class HorairesDisplayer(LBox):
    def __init__(self):
        LBox.__init__(self, orientation="vertical")
        self.getter = HorairesGetter(gare_from, gare_to)
        self.build_info()
        gobject.timeout_add_seconds(refresh_seconds, self.update_info)
        self._build_background()

    def build_info(self):
        self.info = i = Label()
        i.show()
        i.set_color(alwaysontop.font_color)
        i.set_font_name(alwaysontop.font_name)
        i.set_text("Horaires des trains")
        self.add(i)

    def update_info(self):
        s = self.getter.get_trains_desc()
        self.info.set_text(s)
        return True

class HorairesGetter(object):
    def __init__(self, code_gare_from, code_gare_to):
        self.url = "http://www.transilien.com/web/ITProchainsTrainsAvecDest.do?codeTr3aDepart=%s&codeTr3aDest=%s&urlModule=/site/pid/184&gareAcc=true" %(code_gare_from, code_gare_to)
        print self.url
        self.stag = horaire_start_tag = '<td headers="Heure_de_passage">'
        self.etag = horaire_end_tag = '</td>'

    def get_trains_desc(self):
        l = self.get_trains()
        s = "Prochains RER C"
        for item in l:
            s = "%s\n%s" %(s, item)
        return s

    def get_trains(self):
        self.trains = list()
        u = urlopen(self.url)
        t = u.read()
        self.parse_result(t)
        return self.trains

    def parse_result(self, t):
        startPos = t.find(self.stag)
        while startPos > -1:
            endPos = t.find(self.etag,startPos+1)
            if endPos == -1:
                break
            else:
                horaire = t[startPos+len(self.stag):endPos].strip()
                train = t[startPos-len(self.stag)-77:startPos].split("</a>")[0]
                if train == "SARA" or train == "LARA":
                    print "train direct : %s à %s" %(train, horaire)
                else:
                    print "train lent : %s à %s" %(train, horaire)
                self.trains.append("%s:%s" %(train, horaire))
                startPos = t.find(self.stag,endPos+1)


